#include <bits/stdc++.h>


#define DEBUG 1
#define IS_REUSED_PORT 1
#define IS_NOBLOCK 0
#define SOCKET_BUFFER 256
#define PARSE_CONFIG_FILE_FROM_C 1
#define CONFIG_MAX_LINE_LENGTH 256

using namespace std;

enum SORT{
    SELECT = 1,
    INSERT,
    QUICK,
    HEAP,
    MERGE
};

enum SEARCH{
    BINARY = 1
};

typedef struct g_config_s {
    bool is_network;
    bool is_server;
    bool is_quit;
    bool is_client;
    bool is_algorithm;
    short port;
    char * host;
    SORT sort;
    SEARCH search;
} g_config_t;

g_config_t conf;


template<typename T>
class m_shared_ptr{
public:
    constexpr m_shared_ptr() noexcept :ptr(nullptr), ref_count(nullptr){}
    // 空指针构造
    constexpr m_shared_ptr(std::nullptr_t) noexcept :ptr(nullptr), ref_count(nullptr){}
    // 原始指针构造
    explicit m_shared_ptr(T * p) :ptr(p), ref_count(p ? new size_t(1) : nullptr){}
    // 拷贝构造函数
    m_shared_ptr(const m_shared_ptr & other) noexcept :ptr(other.ptr), ref_count(other.ref_count){
        if(ref_count){
            ++(*ref_count);
        }
    }
    // 模板拷贝构造函数 (支持派生类到基类的转换)
    template<typename U>
    m_shared_ptr(const m_shared_ptr<U> & other) noexcept :ptr(other.ptr), ref_count(other.ref_count){
        if(ref_count){
            ++(*ref_count);
        }
    }

    // 移动构造函数
    m_shared_ptr(m_shared_ptr && other) noexcept :ptr(other.ptr), ref_count(other.ref_count){
        other.ptr = nullptr;
        other.ref_count = nullptr;
    }

    // 模板移动构造函数
    template<typename U>
    m_shared_ptr(m_shared_ptr<U> && other) noexcept: ptr(other.ptr), ref_count(other.ref_count){
        other.ptr = nullptr;
        other.ref_count = nullptr;
    }

    ~m_shared_ptr(){
        release();
    }

    // 拷贝赋值
    m_shared_ptr & operator=(const m_shared_ptr & other) noexcept{
        if(this != &other){
            release();
            ptr = other.ptr;
            ref_count = other.ref_count;
            if(ref_count){
                ++(*ref_count);
            }
        }
        return *this;
    }

    // 移动赋值
    m_shared_ptr & operator=(m_shared_ptr && other) noexcept{
        if(this != &other){
            release();
            ptr = other.ptr;
            ref_count = other.ref_count;
            other.ptr = nullptr;
            other.ref_count = nullptr;
        }
        return *this;
    }

    void reset() noexcept{
        release();
        ptr = nullptr;
        ref_count = nullptr;
    }

    void reset(T * p){
        if(ptr != p){
            release();
            ptr = p;
            ref_count = p ? new size_t(1) : nullptr;
        }
    }

    void m_swap(m_shared_ptr & other) noexcept{
        std::swap(ptr, other.ptr);
        std::swap(ref_count, other.ref_count);
    }

    T * get() const noexcept{
        return ptr;
    }

    T & operator*() const noexcept{
        return *ptr;
    }

    T * operator->() const noexcept{
        return ptr;
    }

    explicit operator bool() const noexcept{
        return ptr != nullptr;
    }

    size_t use_count() const noexcept{
        return ref_count ? * ref_count : 0;
    }

private:
    T * ptr;
    size_t * ref_count;

    template<typename U>
    friend class m_shared_ptr;

    void release(){
        if(ref_count && --(*ref_count) == 0){
            delete ptr;
            delete ref_count;
        }
    }
};

template<typename T, typename ... Args>
m_shared_ptr<T> m_make_shared(Args && ... args){
    return m_shared_ptr<T>(new T(std::forward<Args>(args)...));
}

template<typename T>
void swap(m_shared_ptr<T> & a, m_shared_ptr<T> & b){
    a.m_swap(b);
}

template<typename T, typename U>
bool operator==(const m_shared_ptr<T> & a, const m_shared_ptr<U> & b) noexcept {
    return a.get() == b.get();
}

template<typename T>
bool operator==(const m_shared_ptr<T> & a, std::nullptr_t) noexcept{
    return !a;
}

template<typename T>
bool operator==(std::nullptr_t, const m_shared_ptr<T> & a) noexcept{
    return !a;
}


void test_m_shared_ptr(){
    typedef m_shared_ptr<int> intPtr;

    intPtr sp1(new int(20));
    cout << "sp1 value: " << *sp1 << ", use count: " << sp1.use_count() << endl;
    {
        intPtr sp2 = sp1;
        cout << "sp1 use count : " << sp1.use_count() << endl;
        cout << "sp2 use count : " << sp2.use_count() << endl;
    }
    cout << "sp1 use count : " << sp1.use_count() << endl;

    intPtr sp3 = std::move(sp1);
    cout << "sp3 use count : " << sp3.use_count() << endl;
    cout << "sp1 after move : " << (sp1 ? "not null" : "null") << endl;

    auto sp4 = m_make_shared<std::string>("aaa");
    cout << "sp4 : " << *sp4 << endl;

    struct Base{
        virtual ~Base() = default;
    };
    struct Derived :public Base{};

    m_shared_ptr<Derived> derived(new Derived());
    m_shared_ptr<Base> base = derived;
    cout << "Derived use count : " << derived.use_count() << endl;
    cout << "Base use count : " << base.use_count() << endl;

    /**
    sp1 value: 20, use count: 1
    sp1 use count : 2
    sp2 use count : 2
    sp1 use count : 1
    sp3 use count : 1
    sp1 after move : null
    sp4 : aaa
    Derived use count : 2
    Base use count : 2
     * */

}


#ifdef __cplusplus
extern "C"
{
#endif

#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdbool.h>
#include <signal.h>

void signal_handle(int signum){
    if(signum == SIGINT || signum == SIGTERM){
        conf.is_quit = true;
        printf("signal-quit:  %d \n", signum);
    }
}

// 服务器
int init_socket(bool isServer){
    int fd;
    fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in address;
    bzero(&address, sizeof(address));

    if(isServer){
        address.sin_port = conf.port;
        address.sin_addr.s_addr = htonl(INADDR_ANY);
        address.sin_family = AF_INET;
    } else {
        address.sin_port = conf.port;
        address.sin_addr.s_addr = inet_addr(conf.host);
        address.sin_family = AF_INET;
    }


#if IS_NOBLOCK
    int opt = fcntl(fd, F_GETFL);
    fcntl(fd, F_SETFL, opt | O_NONBLOCK);
#endif

#if IS_REUSED_PORT
    int reuse = 1;
    if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))){
        exit(1);
    }
    if(setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse))){
        exit(1);
    }
#endif

    if(isServer) {
        if (bind(fd, (struct sockaddr *) &address, sizeof(address))) {
            exit(1);
        }
        if (listen(fd, 64)) {
            exit(1);
        }
    }else{
        if(connect(fd, (struct sockaddr *)&address, sizeof(address))){
            exit(1);
        }
    }
    return fd;
}

void start_server(){
    printf("-------start_server---------------\n");
    struct sockaddr_in clientaddr;
    socklen_t len = sizeof (clientaddr);
    int socket_fd = init_socket(conf.is_server);
    printf("------socket_fd--------%d \n", socket_fd);
    int client_fd = accept(socket_fd,(struct sockaddr *)&clientaddr, &len);
    while(1){
        char buf[SOCKET_BUFFER] = {0};
        int recv_num = recv(client_fd, buf, SOCKET_BUFFER, 0);
        if(0 == recv_num){
            printf("  close fd %d  \n", client_fd);
            break;
        }
        printf("recv  %s \n", buf);
        send(client_fd, buf, recv_num, 0);
    }
    close(client_fd);
}

//  客户端
void start_client() {
    printf("--------start_client--------------\n");
    int fd = init_socket(conf.is_client);
    printf("--------fd------%d \n", fd);
//    signal(SIGINT, signal_handle);
//    signal(SIGTERM, signal_handle);
    char buf[SOCKET_BUFFER] = {0};
    while(!conf.is_quit){
        fgets(buf, sizeof(buf), stdin);
        send(fd, buf, sizeof(buf), 0);
        printf("send: %s \n", buf);
        int recv_num = recv(fd, buf, sizeof(buf), 0);
        if(recv_num > 0){
            printf("send %s \n", buf);
        }else{
            break;
        }
    }
    close(fd);
}


#if PARSE_CONFIG_FILE_FROM_C




void load_file(const char * filename = "./config.conf"){
    FILE * file = fopen(filename, "r");
    if(!file){
        printf("-----file open error---------- \n");
    }
    char buf[CONFIG_MAX_LINE_LENGTH] = {0};
    bool annotation_flag = false;
    while(fgets(buf, CONFIG_MAX_LINE_LENGTH, file) != NULL){
        printf("%s", buf);
        char * line = buf;
        if(*line == '#' || *line == '\n') continue;
        int f = 1;
        bool skip_line = false;
        char * start = line;
        for(;!skip_line;){

            for(;*start != '\n'; start++){
                if(*start != ' ' && !annotation_flag){
                    if(*start == '#'){
                        skip_line = true;
                        break;
                    }
                    if(*start == '/' && *(start+1) == '*'){
                        annotation_flag = true;
                        continue;
                    }
                    break;
                }

                if(annotation_flag){
                    if(*start == '*' && *(start + 1) == '/'){
                        start += 2;
                        annotation_flag = false;
                    }
                    continue;
                }
            }
            if(skip_line || *start == '\n') break;
            char * end = start+1;
            for(;*end != '\n' && *end != ' '; end++){
                if(!annotation_flag){
                    if(*end == '/' && *(end+1) == '*'){
                        annotation_flag = true;
                        continue;
                    }
                    if(*end == '#'){
                        skip_line = true;
                        *end = '\0';
                        break;
                    }
                }
                if(annotation_flag){
                    if(*end == '*' && *(end + 1) == '/'){
                        end += 2;
                        annotation_flag = false;
                    }
                    continue;
                }
            }
            if(*end == '\n') skip_line = true;
            *end = '\0';
            if(f){
                printf("key:%s,", start);
                f ^= 1;
            }else{
                printf("value:%s,", start);
            }
            start = end + 1;
            if(end == start || *end == '\n') break;
        }
        printf("-----------new line-------------\n");
        memset(buf, 0, CONFIG_MAX_LINE_LENGTH);
    }
    fclose(file);
}

#endif


#ifdef __cplusplus
}
#endif





/**
 *  -m  mod
 *      nt -- network
 *  -S  server
 *  -p  port
 *  -h  host
 * **/
int parse_args(int argc, char * argv[]){
    int opt;
    while((opt = getopt(argc, argv, "m:p:h:S::C::")) != -1){
        switch (opt) {
            case 'm':
#if DEBUG
                printf("-m:  %s \n", optarg);
#endif
                break;
            case 'S':
                conf.is_server = true;
#if DEBUG
                printf("-S:  %s \n", optarg);
#endif
                break;
            case 'C':
                conf.is_client = true;
                break;
            case 'p':
                conf.port = htons(atoi(optarg));
                break;
            case 'h':

//                conf.host = optarg;
                printf("h:   %s \n", optarg);
                conf.host = (char *)malloc(sizeof(optarg)+1);
                strcpy(conf.host, optarg);
                break;
            default:
                return -1;
        }
    }
    return 0;
}

void printConf(){
    cout << "is server: " << boolalpha << conf.is_server << endl;   // false
    cout << "is client: " << boolalpha << conf.is_client << endl;   // false
    cout << "port: " << conf.port << ",  " << ntohs(conf.port) << endl;
    cout << "host: " << conf.host << endl;
    struct in_addr addr;
    addr.s_addr= inet_addr(conf.host);
    cout << "host--- : " << inet_ntoa(addr) << endl;

}

void network_mode(){
    if(conf.is_server){
        start_server();
    }
    if(conf.is_client){
        start_client();
    }
}



//---------------------------------------------
namespace my_traits{

template<bool B>
struct bool_type{  static constexpr bool value = false; };

template<>
struct bool_type<true>{  static constexpr bool value = true;  };

using true_type = bool_type<true>;
using false_type = bool_type<false>;

template<typename T>
struct always_false :public false_type {};

template<typename A, typename B>
struct is_same :public false_type {};

template<typename A>
struct is_same<A, A> :public true_type {};

//  c++ 14
template<typename A, typename B>
using is_same_v = typename is_same<A, B>::value;


template<typename ... T>
struct make_void{   using type = void;  };

template<typename ... T>
using void_t = typename make_void<T...>::type ;

template<typename T>
struct is_array :public false_type {};
template<typename T, size_t N>
struct is_array<T[N]> :public true_type {};
template<typename T>
struct is_array<T[]> :public true_type {};
template<typename T>
constexpr bool is_array_v = is_array<T>::value;

template<typename T>
struct is_pointer :public false_type {};

template<typename T>
struct is_pointer<T *> :public true_type {};

template<typename T>
constexpr bool is_pointer_v = is_pointer<T>::value;


template<typename T>
struct is_reference :public false_type {};
template<typename T>
struct is_reference<T &> :public true_type {};
template<typename T>
struct is_reference<T&&> :public true_type {};
template<typename T>
constexpr bool is_reference_v = is_reference<T>::value;

template<typename T>
struct add_const{using type = const T; };
template<typename T>
struct add_const<const T>{ using type = const T; };
template<typename T>
using add_const_t = typename add_const<T>::type ;
template<typename T>
struct is_const :public false_type {};
template<typename T>
struct is_const<const T> :public true_type {};
template<typename T>
constexpr bool is_const_v = is_const<T>::type;

template<typename T>
struct remove_reference { using type = T; };

template<typename T>
struct remove_reference<T &>{ using type = T; };

template<typename T>
struct remove_reference<T && > { using type = T; };

template<typename T>
using remove_reference_t = typename remove_reference<T>::type;


template<typename T>
struct add_lvalue_reference {     using type = typename remove_reference<T>::type &; };
template<typename T>
using add_lvalue_reference_t = typename add_rvalue_reference<T>::type;


template<typename T>
struct add_rvalue_reference {      using type = typename remove_reference<T>::type &&; };

template<typename T>
struct remove_cv{ using type = T; };
template<typename T>
struct remove_cv<const T>{ using type = T; };
template<typename T>
struct remove_cv<volatile T>{ using type = T; };
template<typename T>
struct remove_cv<const volatile T>{ using type = T; };
template<typename T>
using remove_cv_t = typename remove_cv<T>::type;

template<typename T>
struct is_null_pointer :public bool_type< is_same<decltype(nullptr) , typename remove_cv<T>::type >::value >{};

template<typename T>
constexpr bool is_null_pointer_v = is_null_pointer<T>::value;


template<typename T>
T && forward(typename remove_reference<T>::type & t) noexcept{ return static_cast<T && >(t); }
template<typename T>
T && forward(typename remove_reference<T>::type && t) noexcept{ return static_cast<T &&>(t); }
template<typename T>
constexpr typename remove_reference<T>::type && move(T && arg) noexcept{ return static_cast<typename remove_reference<T>::type&&>(arg); }


template<typename T>
struct decay_non_reference{ using type = remove_cv_t<T>; };
template<typename T>
struct decay_non_reference<T[]>{ using type = T *; };
template<typename T, size_t N>
struct decay_non_reference<T[N]>{ using type = T*; };

template<typename T>
struct decay{ using type = typename decay_non_reference<remove_reference<T>>::type; };
template<typename T>
using decay_t = typename decay<T>::type ;

template<bool Test, typename T = void>
struct enable_if{};

template<typename T>
struct enable_if<true, T>{ using type = T; };
template<bool Test, typename T = void>
using enable_if_t = typename enable_if<Test, T>::type;

template<bool Test, typename T>
struct lazy_enable_if{};
template<typename T>
struct lazy_enable_if<true, T>{ using type = T; };
template< bool Test, typename T = void>
using lazy_enable_if_t = typename lazy_enable_if<Test, T>::type;



template <bool COND, typename T1, typename T2>
struct condition_type { typedef T1 type; };
template <typename T1, typename T2>
struct condition_type<false, T1, T2> { typedef T2 type; };
template <bool COND, typename T1, typename T2>
using condition_type_t = typename condition_type<COND, T1, T2>::type;
template <bool COND, typename T, T TRUE_VALUE, T FALSE_VALUE>
struct condition_value { static constexpr T value = TRUE_VALUE; };
template <typename T, T TRUE_VALUE, T FALSE_VALUE>
struct condition_value<false, T, TRUE_VALUE, FALSE_VALUE> { static constexpr T value = FALSE_VALUE; };
template <bool COND, typename T, T TRUE_VALUE, T FALSE_VALUE>
constexpr T condition_value_v = condition_value<COND, T, TRUE_VALUE, FALSE_VALUE>::value;


    // 定义一个模板结构体，用于根据类型T的析构特性选择不同的析构方式
    template<typename T>
    struct object_destructor{
    private:
        // 定义两种标记类型，用于区分平凡析构和非平凡析构
        struct trivial_destructor_type{};    // 标记平凡析构类型
        struct non_trivial_destructor_type{}; // 标记非平凡析构类型

        // 模板结构体，根据不同的析构类型特化不同的析构实现
        template<typename U, typename destructor_type>
        struct destructor_impl;

        // 特化版本：处理平凡析构类型（不需要显式调用析构函数）
        template<typename U>
        struct destructor_impl<U, trivial_destructor_type>{
            static inline void destruct(U * _ptr){
                (void)_ptr;  // 无操作，只是为了避免未使用参数的警告
            }
        };

        // 特化版本：处理非平凡析构类型（需要显式调用析构函数）
        template<typename U>
        struct destructor_impl<U, non_trivial_destructor_type>{
            static inline void destruct(U * _ptr){
                if(_ptr){  // 检查指针是否非空
                    _ptr->~T();  // 显式调用析构函数
                }
            }
        };

    public:
        // 公开的析构接口函数
        static inline void destruct(T * _ptr){
            // 根据T是否是平凡可析构的，选择适当的析构类型标记
            using destructor_type = typename condition_type<is_trivially_destructible<T>::value,
                    trivial_destructor_type,
                    non_trivial_destructor_type>::type;

            // 调用相应的析构实现
            destructor_impl<T, destructor_type>::destruct(_ptr);
        }
    };


    // 模板函数：将输入值向上取整为不小于它的最小2的幂次方
    // 例如：输入5返回8，输入8返回8，输入17返回32
    template <typename T>
    inline T roundup_pow_of_two(T x)
    {
        // 首先检查x是否已经是2的幂次方
        // 原理：2的幂次方的二进制表示只有1个1（如8=1000）
        // x & (x-1)会把这个1去掉（如8&7=1000&0111=0000）
        if ((x & (x - 1)) == 0) {
            return x;  // 如果已经是2的幂次方，直接返回
        }

        T result = 1;  // 初始化结果为1（2^0）

        // 通过右移x直到它为0，同时左移result
        // 这个循环计算的是能覆盖x的最小2的幂次方
        while (x > 0) {
            x = x >> 1;    // 右移x一位（相当于x/2）
            result = result << 1;  // 左移result一位（相当于result*2）
        }

        return result;  // 返回计算结果
    }

    /**
     * @brief 计算以null结尾的字符串的长度（通用模板）
     * @tparam CHAR_TYPE 字符类型（如char, wchar_t等）
     * @param str 输入字符串指针
     * @return 字符串长度（不包含结尾的null字符），如果str为nullptr则返回0
     * @note 这是一个constexpr函数，可以在编译期计算常量字符串的长度
     */
    template<typename CHAR_TYPE>
    inline size_t __string_len(const CHAR_TYPE* str) {
        if (!str) {  // 处理空指针情况
            return 0;
        }
        const CHAR_TYPE* str_start = str;  // 记录起始位置
        for (; *str; ++str) {}  // 遍历直到遇到null字符
        return (size_t)(str - str_start);  // 指针相减得到长度
    }

    /**
     * @brief 特化版本：针对char类型的字符串长度计算
     * @param str 输入字符串指针（char类型）
     * @return 字符串长度（不包含结尾的null字符），如果str为nullptr则返回0
     * @note 使用标准库的strlen()实现以获得更好的性能
     * @note 定义为inline函数以减少函数调用开销
     */
    template<>
    inline size_t __string_len(const char* str) {
        if (!str) return 0;  // 处理空指针情况
        return strlen(str);  // 调用标准库函数
    }

    template<typename CHAR_TYPE>
    inline const CHAR_TYPE * __find_char(const CHAR_TYPE * str, const CHAR_TYPE c){
        if(!str) return nullptr;
        for(; *str; ++str)
            if(*str == c)
                return str;

        return nullptr;
    }

    template<typename CHAR_TYPE>
    inline const CHAR_TYPE * __strstr(const CHAR_TYPE * str, const CHAR_TYPE * sub_str){
        if(!str) return nullptr;
        auto sub_len = __string_len(sub_str);
        if(0 == sub_len) return nullptr;
        auto str_len = __string_len(str);
        const CHAR_TYPE * begin_pos = __find_char(str, *sub_str);
        while(begin_pos && begin_pos + sub_len <= str + str_len){
            if(memcmp(begin_pos, sub_str, sub_len * sizeof(CHAR_TYPE)) == 0)
                return begin_pos;
            begin_pos = __find_char(begin_pos+1, *sub_str);
        }
        return nullptr;
    }


    enum class enum_new_dummy {
        dummy
    };
    
    // 这是一个包装结构体，用于定义数据对齐方式
    // 在C++17及以下标准中，"alignas"关键字仅能保证堆分配时的对齐
    // 当使用"placement new"且起始地址未对齐时，"alignas"无法正常工作
    // ***重要提示：此实现可能会引入一定的性能开销
    template <typename T, uint32_t align>
    struct aligned_type;

    // 类型特征模板，用于识别普通类型（默认返回false）
    template <typename T>
    struct is_aligned_type : public false_type {};

    // 特化版本，当类型为aligned_type时返回true
    template <typename T, uint32_t align>
    struct is_aligned_type<aligned_type<T, align>> : public true_type {};

// 对齐类型主模板实现
template <typename T, uint32_t align>
struct aligned_type {
private:
    // 用于存储对齐偏移量的类型
    typedef uint32_t offset_type;
    // 静态断言确保偏移量类型不超过4字节
    static_assert(sizeof(offset_type) <= 4, "offset_type大小应<=4");
    // 用于地址对齐计算的掩码
    static constexpr size_t offset_mask = ~(sizeof(offset_type) - 1);

    // 偏移量存储区（多分配一倍空间确保后续对齐）
    uint8_t offset_[sizeof(offset_type) + sizeof(offset_type)];
    // 数据存储区（包含对齐填充空间和对象存储空间）
    uint8_t padding_[align + sizeof(T)];

private:
    // 获取偏移量引用（保证对齐访问）
    uint32_t& offset() const
    {
        // 计算对齐后的偏移量存储地址
        return *(uint32_t*)(((size_t)offset_ + (sizeof(offset_type) - 1)) & offset_mask);
    }

    // 初始化函数，计算所需对齐偏移量
    void init()
    {
        size_t addr = (size_t)padding_;
        uint32_t mod = (uint32_t)(addr % align);
        if (mod == 0) {
            offset() = 0;  // 已经对齐，偏移量为0
        } else {
            offset() = (uint32_t)align - mod;  // 计算需要补充的偏移量
        }
    }

    // 获取对齐后的对象地址
    void* get_addr() const
    {
        return (void*)(padding_ + offset());
    }

public:
    // 默认构造函数
    aligned_type()
    {
        init();
        // 在对齐地址上使用placement new构造对象
        new (get_addr(), enum_new_dummy::dummy) T();
    }

    // 析构函数
    ~aligned_type()
    {
        // 调用对象析构函数
        object_destructor<T>::destruct((T*)get_addr());
    }

    // 拷贝构造函数
    inline aligned_type(const aligned_type<T, align>& rhs)
    {
        init();
        new (get_addr(), enum_new_dummy::dummy) T(rhs.get());
    }

    // 移动构造函数（noexcept保证不抛出异常）
    inline aligned_type(aligned_type<T, align>&& rhs) noexcept
    {
        init();
        new (get_addr(), enum_new_dummy::dummy) T(move(rhs.get()));
    }

    // 模板化拷贝构造（支持不同对齐参数）
    template <typename U, uint32_t U_align>
    inline aligned_type(const aligned_type<U, U_align>& rhs)
    {
        init();
        new (get_addr(), enum_new_dummy::dummy) T(rhs.get());
    }

    // 模板化移动构造（支持不同对齐参数）
    template <typename U, uint32_t U_align>
    inline aligned_type(aligned_type<U, U_align>&& rhs) noexcept
    {
        init();
        new (get_addr(), enum_new_dummy::dummy) T(move(rhs.get()));
    }

    // 通用构造函数（处理非aligned_type参数）
    template <typename U, typename enable_if<!is_aligned_type<typename decay<U>::type>::value>::type* = nullptr>
    inline aligned_type(U&& init_value)
    {
        init();
        new (get_addr(), enum_new_dummy::dummy) T(forward<U>(init_value));
    }

    // 拷贝赋值运算符
    inline aligned_type<T, align>& operator=(const aligned_type<T, align>& rhs)
    {
        get() = rhs.get();
        return *this;
    }

    // 移动赋值运算符（noexcept保证不抛出异常）
    inline aligned_type<T, align>& operator=(aligned_type<T, align>&& rhs) noexcept
    {
        get() = move(rhs.get());
        return *this;
    }

    // 模板化拷贝赋值（支持不同对齐参数）
    template <typename U, uint32_t U_align>
    inline aligned_type<T, align>& operator=(const aligned_type<U, U_align>& rhs)
    {
        get() = rhs.get();
        return *this;
    }

    // 模板化移动赋值（支持不同对齐参数）
    template <typename U, uint32_t U_align>
    inline aligned_type<T, align>& operator=(aligned_type<U, U_align>&& rhs) noexcept
    {
        get() = move(rhs.get());
        return *this;
    }

    // 通用赋值运算符（处理非aligned_type参数）
    template <typename U, typename enable_if<!is_aligned_type<typename decay<U>::type>::value>::type* = nullptr>
    inline aligned_type<T, align>& operator=(U&& value)
    {
        get() = forward<U>(value);
        return *this;
    }

    // 获取存储对象的引用（非const版本）
    inline T& get()
    {
        return *(T*)get_addr();
    }

    // 获取存储对象的引用（const版本）
    inline const T& get() const
    {
        return *(const T*)get_addr();
    }
};

template<typename T>
struct cache_friendly_type{  // 防止伪共享(false sharing)
    static constexpr size_t CACHE_LINE_SIZE = 64;
    uint8_t padding_left[CACHE_LINE_SIZE];
    T value;
    uint8_t padding_right[CACHE_LINE_SIZE];
    /**
     *   // 使用 alignas 确保 value_ 独占一个缓存行 兼容性最好
     *   alignas(CACHE_LINE_SIZE) T value_;
     *
     *   // c++ 17: hardware_destructive_interference_size
     *   alignas(std::hardware_destructive_interference_size) T value_;
     *
     *   // 多线程共享变量
     *   alignas(CACHE_LINE_SIZE) std::atomic<T> value_;
     *
     *   // 判断 sizeof(T) <= cache_line_size;
     *   T value;
     *   std::array<uint8_t, CACHE_LINE_SIZE - sizeof(T)> padding_;
     * **/

public:
    // 使用完美转发保持值类别
    template<typename U>
    cache_friendly_type(U && rhs) :value(forward<U>(rhs)){}

    T& get(){return value; }
    const T & get() const { return value; }
};




    // 定义一个模板类，用于管理动态分配的对象，确保其生命周期受限于作用域
    template <typename T>
    struct scoped_obj {
    private:
        T* ptr;  // 指向动态分配的对象的指针

    public:
        // 默认构造函数，初始化指针为 nullptr
        scoped_obj() : ptr(nullptr){}

        // 带参数的构造函数，接受一个指向 T 类型对象的指针
        scoped_obj(T* new_obj){ ptr = new_obj; }

        // 禁用拷贝赋值运算符，防止资源重复释放
        scoped_obj& operator=(const scoped_obj& rhs) = delete;

        // 析构函数，释放管理的对象
        ~scoped_obj() {
            if (ptr) {
                delete ptr;  // 如果指针非空，释放对象
            }
        }

        // 重载箭头运算符，提供对管理对象的成员访问
        T* operator->(){return ptr;}

        // 转移指针所有权，返回当前指针并将内部指针置为 nullptr
        T* transfer(){
            T* tmp = ptr;
            ptr = nullptr;
            return tmp;
        }
    };

    template<typename T>
    class unique_ptr{
    private:
        T * ptr;
        template<typename>
        friend class unique_ptr;
    public:
        unique_ptr():ptr(nullptr){}
        unique_ptr(T * new_ptr) :ptr(new_ptr) {}

        template<typename U>
        unique_ptr(unique_ptr<U> && rhs) noexcept :ptr(rhs.ptr){ rhs.ptr = nullptr; }

        unique_ptr(const unique_ptr & ) = delete;  // 独占所有权
        unique_ptr & operator=(const T &) = delete;  // 独占所有权
        unique_ptr & operator=(T *) = delete;  // 禁用从原始指针的赋值 避免隐式所有权转移

        template<typename U>
        unique_ptr & operator=(unique_ptr<U> && rhs){
            if(ptr != rhs.ptr){
                reset();
                ptr = rhs.ptr;
                rhs.ptr = nullptr;
            }
            return *this;
        }
        T * operator->(){ return ptr; }
        const T * operator->() const { return ptr; }
        T & operator*(){ return *ptr; }
        const T & operator*() const { return *ptr; }

        // 类型转换运算符，将 unique_ptr 隐式转换为 void*
        operator void *() const{ return static_cast<void *>(ptr); }
        ~unique_ptr(){ reset(); }
        void reset(){
            if(ptr)
                delete ptr;
            ptr = nullptr;
        }

        template<typename U>
        void swap(unique_ptr<U> & rhs){
            auto old = ptr;
            ptr = rhs.ptr;
            rhs.ptr = old;
        }
        T * get(){ return ptr; }
        template<typename U>
        bool operator==(const unique_ptr<U> & rhs) const { return ptr == rhs.operator->();}
    };

    template<typename T, typename ... Args>
    unique_ptr<T> make_unique(Args && ... args){ return unique_ptr<T>(new T(forward<T>(args)...)); }

    // 分配一块 没有初始化的内存由 unique_ptr 管理；
    // 适用于需要手动初始化或性能敏感的场景（避免不必要的默认构造）
    // 需要手动初始化对象（如直接通过 memcpy、placement new 等方式填充数据）。
    template<typename T>
    unique_ptr<T> make_unique_for_overwrite(){ return unique_ptr<T>(new T); }





    template<typename T, typename ARRAY>
    class array_iter{
    public:
        template<typename V, typename V_ARRAY>
        friend class array_iter;

        template<typename V, size_t BUF_SIZE>
        friend class array_base;

        using value_type = typename remove_reference<T>::type;
        using diff_type = ::ptrdiff_t;
        using size_type = typename ARRAY::size_type;
    private:
        value_type * data_;
        const typename ARRAY::value_type * array_data_ptr_;

    public:
        template<typename V>
        array_iter(V * ptr, const ARRAY * arr_ptr = nullptr);
        template<typename V, typename V_ARRAY>
        array_iter(const array_iter<V, V_ARRAY> & rhs);
        template<typename V, typename V_ARRAY>
        array_iter<V, V_ARRAY> & operator=(const array_iter<V, V_ARRAY> & rhs){
            data_ = rhs.data_;
            array_data_ptr_ = rhs.array_data_ptr_;
            return *this;
        }

    public:
        template<typename T1, typename T2, typename V_ARRAY_1, typename V_ARRAY_2>
        friend bool operator==(const array_iter<T1, V_ARRAY_1> & arr1, const array_iter<T2, V_ARRAY_2> & arr2);
        // != < <= > >=
        template<typename T1, typename T2, typename V_ARRAY_1, typename V_ARRAY_2>
        friend typename array_iter<T1, V_ARRAY_1>::diff_type operator-(const array_iter<T1, V_ARRAY_1> & arr1, const array_iter<T2, V_ARRAY_2> & arr2){
            assert((arr1.array_data_ptr_ == arr2.array_data_ptr_) && "you can not sub two arr_iter generated from different arr");
            return arr1.data_ - arr2.data_;
        }

    public:
        array_iter<T, ARRAY> & operator++();  // 前置++
        array_iter<T, ARRAY> & operator++(int32_t); // 后置++
        array_iter<T, ARRAY> & operator+=(int32_t value) {
            data_ += value;
            return *this;
        }
        array_iter<T, ARRAY> & operator+=(size_type value){
            data_ += (int32_t)value;
            return *this;
        }
        // -- + - -=

        value_type & operator*() const { return *data_; }
        value_type * operator->() const{ return data_; }
        operator value_type *() const { return data_; }  // 将迭代器隐式转换为原始指针
    };

    template<typename T, size_t BUF_SIZE = 0>
    class array_base{
    public:
        using value_type = typename decay<T>::type;
        using size_type = size_t;
        using iterator = array_iter<value_type, array_base<T, BUF_SIZE>>;
        using const_iterator = array_iter<const value_type, array_base<T, BUF_SIZE>>;

        template<typename V, size_t BUF_SIZE_V>
        friend class array_base;
        friend class array_iter<value_type, array_base<T, BUF_SIZE> >;
        friend class array_iter<const value_type, array_base<T, BUF_SIZE> >;

    protected:
        value_type * data_;
        size_type size_;
        size_type capacity_;

    public:
        array_base();
        ~array_base();
        // 列表初始化
        template<typename First, typename Second, typename ... Rest>
        array_base(First && first, Second && second, Rest && ... rest);
        // 单一元素构造
        array_base(const T & rhs);
        array_base(T && rhs) noexcept;
        // 从另一个数组多元素构造
        array_base(const array_base<T, BUF_SIZE> & rhs);
        array_base(array_base<T, BUF_SIZE> && rhs) noexcept;

        size_type size() const{ return size_; }
        size_type capacity() const { return capacity_; }
        bool is_empty() const{ return size_ == 0; }

        value_type & operator[](size_type idx);
        const value_type & operator[](size_type idx) const ;

        template<typename T1, typename T2, size_t S1, size_t s2>
        friend bool operator==(const array_base<T1, S1> & a1, const array_base<T2, S2> & a2);
        // !=

        array_base<T, BUF_SIZE> & operator=(const array_base<T, BUF_SIZE> & rhs);
        // move

        template<typename ... V>
        void insert(iterator dst, V && ... v);
        void insert_batch(iterator dst, iterator src, size_type count);

        template<typename ...V>
        size_type push_back(V && ... v);
        template<typename ... V>
        size_type emplace_back(V && ...v);
        template<typename ... V>
        size_type emplace(iterator where_it, V && ... v);
        // fill_uninitialized

        void pop_back();
        void pop_back(size_type count);
        void erase(size_type count);
        iterator begin();
        iterator end();

        void shrink();
        void clear();

        iterator find(const value_type & value, bool reverse_find = false);
        bool set_capacity(size_type new_capacity, bool force_reset = false);
        // some const function

        bool reset();

    private:
        template<typename ...V>
        void construct(iterator, V && ... args);
        void destruct(iterator it);

        template<class First, typename ... Rest>
        void insert_args_insert(First && first, Rest && ... rest);
    };


    //------------------arr_iterator impl------------------------
    template<typename T, typename ARRAY>
    template<typename V>
    inline array_iter<T, ARRAY>::array_iter(V *ptr, const ARRAY *arr_ptr/* =nullptr */) {
        data_ = ptr;
        array_data_ptr_ = arr_ptr ? arr_ptr->data_ : nullptr;
    }
    template<typename T, typename ARRAY>
    template<typename V, typename V_ARRAY>
    inline array_iter<T, ARRAY>::array_iter(const array_iter<V, V_ARRAY> &rhs) {
        data_ = rhs.data_;
        array_data_ptr_ = rhs.array_data_ptr_;
    }

    template<typename T1, typename T2, typename V_ARRAY_1, typename V_ARRAY_2>
    inline bool operator==(const array_iter<T1, V_ARRAY_1> & arr1, const array_iter<T2, V_ARRAY_2> & arr2){
        return arr1.data_ = arr2.data_;
    }
    template<typename T, typename ARRAY>
    array_iter<T, ARRAY> & array_iter<T, ARRAY>::operator++(){
        data_ += 1;
        return *this;
    }
    template<typename T, typename ARRAY>
    array_iter<T, ARRAY> & array_iter<T, ARRAY>::operator++(int32_t) {
        array_iter<T, ARRAY> tmp = *this;
        operator++();
        return tmp;
    }

    //------------------arr_base impl------------------------
    template<typename T, size_t BUF_SIZE>
    array_base<T, BUF_SIZE>::array_base() :data_(nullptr), size_(0), capacity_(0){}
    template<typename T, size_t BUF_SIZE>
    array_base<T, BUF_SIZE>::array_base(const T &rhs) :data_(nullptr), size_(0), capacity_(0){
        inserter(end(), rhs);
    }
    template<typename T, size_t BUF_SIZE>
    template<typename First, typename Second, typename ... Rest>
    array_base<T, BUF_SIZE>::array_base(First &&first, Second &&second, Rest &&...rest)
                        : data_(nullptr), size_(0), capacity_(sizeof...(rest) + 2){
        set_capacity(capacity_, true);
        insert_args_insert(forward<First>(first), forward<Second>(second), forward<Rest>(rest)...);
    }

    template<typename T, size_t BUF_SIZE>
    array_base<T, BUF_SIZE>::array_base(T &&rhs) noexcept :data_(nullptr), size_(0), capacity_(0){
        inserter(end(), move(rhs));
    }

    template<typename T, size_t BUF_SIZE>
    array_base<T, BUF_SIZE>::array_base(const array_base<T, BUF_SIZE> &rhs) :data_(nullptr), size_(0), capacity_(rhs.size()){
        set_capacity(capacity_, true);
        insert_batch(begin(), rhs.begin(), rhs.size_);
    }
    template<typename T, size_t BUF_SIZE>
    array_base<T, BUF_SIZE>::array_base(array_base<T, BUF_SIZE> &&rhs) noexcept :data_(nullptr), size_(rhs.size), capacity_(rhs.capacity()){
        data_ = rhs.data_;
        rhs.data_ = nullptr;
        rhs.size_ = 0;
        rhs.capacity_ = 0;
    }
    template<typename T, size_t BUF_SIZE>
    typename array_base<T, BUF_SIZE>::value_type & array_base<T, BUF_SIZE>::operator[](size_type idx){
        //  if debug
        // assert(idx < size_);
        return data_[idx];
    }

    template<typename T, size_t BUF_SIZE>
    const typename array_base<T, BUF_SIZE>::value_type & array_base<T, BUF_SIZE>::operator[](size_type idx) const {
        return data_[idx];
    }

    template<typename T1, typename T2, size_t S1, size_t s2>
    bool operator==(const array_base<T1, S1> & a1, const array_base<T2, S2> & a2){
        if(a1.size() != a2.size()) return false;
        for(typename array_base<T1, S1>::size_type i = 0; i < a1.size(); ++i){
            if(a1[i] != a2[i]) return false;
        }
        return true;
    }
    // !=

    template<typename T, size_t BUF_SIZE>
    array_base<T, BUF_SIZE> & array_base<T, BUF_SIZE>::operator=(const array_base<T, BUF_SIZE> & rhs){
        reset();
        data_ = rhs.data_;
        size_ = rhs.size_;
        capacity_ = rhs.capacity_;
        rhs.size_ = 0;
        rhs.data_ = nullptr;
        rhs.capacity_ = 0;
        return *this;
    }

    template<typename T, size_t BUF_SIZE>
    template<typename ... V>
    void array_base<T, BUF_SIZE>::insert(iterator dst, V && ... v){
        // 确保插入位置在合法范围内
        assert(dst  >= begin() && dst <= end() && "dst  mast between  begin and end !");
        // 由于是单个元素插入,插入数量为1
        constexpr size_type count = 1;
        // 计算需要移动的元素个数
        size_type move_count = end() - dst;
        // 计算插入后的新大小
        size_type new_size = size_ + count;
        // 保存目标位置相对于起始位置的偏移量
        size_type diff = dst -begin();
        // 确保容量足够
        set_capacity(new_size);
        // 重新计算目标位置(因为set_capacity可能会导致内存重分配)
        dst = begin() + diff;
        // 将dst之后的元素整体后移count个位置,为新元素腾出空间
        memmove((void *)(end() + count), (void *)(end()), BUF_SIZE * sizeof(value_type));
        __inner_forward_move<typename array_base<T, BUF_SIZE>::value_type>(dst + count, dst, move_count);

        if(move_count > 0){
            destruct(dst);
        }
        construct(dst, forward<V>(v)...);
        size_ = new_size;
    }

    template<typename T, size_t BUF_SIZE>
    void array_base<T, BUF_SIZE>::insert_batch(iterator dst, iterator src, size_type count){

    }

    template<typename T, size_t BUF_SIZE>
    template<typename ...V>
    typename array_base<T, BUF_SIZE>::size_type array_base<T, BUF_SIZE>::push_back(V && ... v){
        insert(end(), forward<V>(v)...);
        return size_;
    }

    template<typename T, size_t BUF_SIZE>
    template<typename ... V>
    typename array_base<T, BUF_SIZE>::size_type array_base<T, BUF_SIZE>::emplace_back(V && ...v){
        return push_back(move(v)...);
    }

    template<typename T, size_t BUF_SIZE>
    template<typename ... V>
    typename array_base<T, BUF_SIZE>::size_type array_base<T, BUF_SIZE>::emplace(iterator where_it, V && ... v){
        return insert(where_it, forward<V>(v)...);
    }

    template<typename T, size_t BUF_SIZE>
    void array_base<T, BUF_SIZE>::pop_back(){
        if(size_ > 0){
            destruct(end() - 1);
            size_--;
        }
    }

    template<typename T, size_t BUF_SIZE>
    void array_base<T, BUF_SIZE>::pop_back(size_type count){
        size_ -= count;
        // object_array_base<T, BUF_SIZE>::pop_back(count);
    }

    template<typename T, size_t BUF_SIZE>
    void array_base<T, BUF_SIZE>::erase(size_type count){

    }

    template<typename T, size_t BUF_SIZE>
    typename array_base<T, BUF_SIZE>::iterator array_base<T, BUF_SIZE>::begin(){

    }

    template<typename T, size_t BUF_SIZE>
    typename array_base<T, BUF_SIZE>::iterator array_base<T, BUF_SIZE>::end(){

    }

    template<typename T, size_t BUF_SIZE>
    void array_base<T, BUF_SIZE>::shrink(){

    }

    template<typename T, size_t BUF_SIZE>
    void array_base<T, BUF_SIZE>::clear(){

    }

    template<typename T, size_t BUF_SIZE>
    typename array_base<T, BUF_SIZE>::iterator array_base<T, BUF_SIZE>::find(const value_type & value, bool reverse_find /* = false */){

    }

    template<typename T, size_t BUF_SIZE>
    bool array_base<T, BUF_SIZE>::set_capacity(size_type new_capacity, bool force_reset/* = false */){

    }


    template<typename T, size_t BUF_SIZE>
    bool array_base<T, BUF_SIZE>::reset(){

    }






}


namespace TODO{

    // 与 标准库 memcmp 比较
    // 对于小内存块(小于 32 字节)，简单实现可能更快
    // 对于中等大小内存块(32-1024 字节)，字长比较效果最好
    // 对于大内存块(>1KB)，SIMD 优化效果显著
    int optimized_memcmp(const void* s1, const void* s2, size_t n) {
        const uint8_t* p1 = static_cast<const uint8_t*>(s1);
        const uint8_t* p2 = static_cast<const uint8_t*>(s2);

        // 比较前几个字节直到对齐
        while (n > 0 && (reinterpret_cast<uintptr_t>(p1) & (sizeof(uintptr_t) - 1)) != 0) {
            if (*p1 != *p2) {
                return (*p1 < *p2) ? -1 : 1;
            }
            p1++;
            p2++;
            n--;
        }

        // 现在指针已对齐，进行字长比较
        const uintptr_t* wp1 = reinterpret_cast<const uintptr_t*>(p1);
        const uintptr_t* wp2 = reinterpret_cast<const uintptr_t*>(p2);

        while (n >= sizeof(uintptr_t)) {
            if (*wp1 != *wp2) {
                // 发现差异，逐字节比较找出具体差异
                const uint8_t* bp1 = reinterpret_cast<const uint8_t*>(wp1);
                const uint8_t* bp2 = reinterpret_cast<const uint8_t*>(wp2);
                for (size_t i = 0; i < sizeof(uintptr_t); ++i) {
                    if (bp1[i] != bp2[i]) {
                        return (bp1[i] < bp2[i]) ? -1 : 1;
                    }
                }
            }
            wp1++;
            wp2++;
            n -= sizeof(uintptr_t);
        }

        // 处理剩余不足一个字长的部分
        p1 = reinterpret_cast<const uint8_t*>(wp1);
        p2 = reinterpret_cast<const uint8_t*>(wp2);
        while (n > 0) {
            if (*p1 != *p2) {
                return (*p1 < *p2) ? -1 : 1;
            }
            p1++;
            p2++;
            n--;
        }

        return 0;
    }
}


int main(int argc, char * argv[]){
    cout << "开始计时：" << endl;
    clock_t start = clock();

//
//    if(parse_args(argc, argv) == -1){
//        cout << "opt error" << endl;
//    }
//    printConf();
//    network_mode();
// ./xx -m nt -p 8989 -h 192.168.1.4 -S

//    load_file("../config.conf");

    test_m_shared_ptr();

//    std::copy(b.begin(), b.end(), std::ostream_iterator<int>(std::cout, " "));
    cout << "耗时: " << clock() - start << endl;
    return 0;
}
